package com.lagou;

import org.apache.catalina.*;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.ServletException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicInteger;

public class SpringApplication {


    private Integer port = 8080;

    private Tomcat tomcat = null;
    private static final AtomicInteger containerCounter = new AtomicInteger(-1);

    public static void run(Class<?> cls,String[] args) throws LifecycleException, IOException, ServletException {
        SpringApplication application = new SpringApplication();
        application.run(args);
    }

    public void run(String[] args) throws LifecycleException, IOException, ServletException {

        initTomcat();
    }

    /**
     * 初始化tomcat
     * @throws LifecycleException
     * @throws IOException
     * @throws ServletException
     */
    private void initTomcat() throws LifecycleException, IOException, ServletException {
        String contextPath = "";
        Path tempBaseDir = Files.createTempDirectory("tomcat-temp-base-dir");//创建临时目录作为tomcat的基础目录
        Path tempDocDir = Files.createTempDirectory("tomcat-temp-doc-dir");//创建临时目录作为应用文档资源的目录

        tomcat = new Tomcat();
        Connector connector = new Connector();
        connector.setPort(port);//设置绑定端口
        tomcat.getService().addConnector(connector);
        tomcat.setConnector(connector);
        tomcat.getHost().setAutoDeploy(false);
        tomcat.setBaseDir(tempBaseDir.toFile().getAbsolutePath());


        StandardContext context = (StandardContext) tomcat.addWebapp(contextPath, tempDocDir.toFile().getAbsolutePath());//创建应用上下文
        context.setParentClassLoader(SpringApplication.class.getClassLoader());
        context.setUseRelativeRedirects(false);

        //tomcat 启动jar扫描设置为跳过所有，避免与框架结合出现 jar file not found exception
        System.setProperty("tomcat.util.scan.StandardJarScanFilter.jarsToSkip", "\\,*");

        tomcat.start();
        startDaemonAwaitThread();

    }
    private void startDaemonAwaitThread() {
        Thread awaitThread = new Thread("container-" + (containerCounter.get())) {

            @Override
            public void run() {
                SpringApplication.this.tomcat.getServer().await();
            }

        };
        awaitThread.setContextClassLoader(getClass().getClassLoader());
        awaitThread.setDaemon(false);
        awaitThread.start();
    }

}
